const util = require('../../utils/util');
const voiceData = require('../../data/voice-data');
const recordMgr = wx.getRecorderManager();
const audioConText = wx.createInnerAudioContext();
const TIME_DOWN_CYCLE = 1000;
const stepCount = 3;
let stepNumber = 1;
const BTN = {
  PLAY: '1',
  REC: '2',
  FINISH: '3',
  PAUSE: '4'
};

let timeDownTimer = null;
let durationTimes = 0;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    timeDown: '00:00 后结束',
    steps: '',
    readDuration: voiceData.duration,
    duration: durationTimes,
    readContent: voiceData.content,
    voiceDescription: '',
    buttonText: '下一步',
    // 重新播放
    showReplay: false,
    // 重新录制
    showRerecord: false,
    // 展示录制
    showRecord: true,
    // 展示完成
    showFinish: false,
    // 展示播放
    showPlay: false,
    showPrevBtn: false,
    playImageUrl: ''
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      showPrevBtn: stepNumber > 1,
      steps: `${stepNumber}/${stepCount}`
    });
    recordMgr.onStart(this.onRecordStart);
    recordMgr.onPause(this.onRecordPause);
    recordMgr.onStop(this.onRecordStop);
    audioConText.onPlay(this.onPlay);
    audioConText.onPause(this.onPause);
    audioConText.onEnded(this.onEnded);
    this.getCountdown(voiceData.expireTime);
    this.showBtn(BTN.REC);
    stepNumber = 1;
  },

  nextStep(e) {
    if (stepNumber === stepCount) {
      return;
    }
    stepNumber++;
    this.setData({
      showPrevBtn: true
    });
    this.setData({
      showPrevBtn: stepNumber > 1,
      steps: `${stepNumber}/${stepCount}`,
      buttonText: stepNumber === stepCount ? '确认提交' : '下一步'
    });
  },

  showBtn(btnName) {
    let btnStatus = {
      // 重新播放
      showReplay: false,
      // 重新录制
      showRerecord: false,
      // 展示录制
      showRecord: false,
      // 展示完成
      showFinish: false,
      // 展示播放
      showPlay: false,
      voiceDescription: ''
    };
    switch (btnName) {
      case BTN.REC:
        btnStatus.showRecord = true;
        btnStatus.voiceDescription = '点击话筒，开始录音';
        btnStatus.duration = 0;
        break;
      case BTN.PLAY:
        btnStatus.showPlay = true;
        btnStatus.showRerecord = true;
        btnStatus.voiceDescription = '录音完毕，请聆听确认后再提交';
        btnStatus.playImageUrl = '/images/play.svg';
        break;
      case BTN.PAUSE:
        btnStatus.showPlay = true;
        btnStatus.showRerecord = true;
        btnStatus.showReplay = true;
        btnStatus.voiceDescription = '录音完毕，请聆听确认后再提交';
        btnStatus.playImageUrl = '/images/pause.svg';
        break;
      case BTN.FINISH:
        btnStatus.showFinish = true;
        btnStatus.voiceDescription = '点击按钮，完成录制';
        break;
    }
    this.setData(btnStatus);
  },

  /**
   * 失效倒计时
   * @param {} endTime 
   */
  getCountdown(endTime) {
    clearInterval(timeDownTimer);
    timeDownTimer = setInterval(() => {
      let { mini, sec, hour, day } = util.timeCounterDown(endTime);
      let timeDown = hour + ':' + mini + ':' + sec;
      if (mini === '00' && sec === '00' && hour === '00' && day === '00') {
        clearInterval(timeDownTimer);
        this.setData({
          timeDown: '已经过期'
        });
      } else {
        this.setData({
          timeDown: `${timeDown} 后结束`
        });
      }
    }, TIME_DOWN_CYCLE);
  },
  /**
   * 点击录音
   */
  tabRecord() {
    this.startRecord();
  },
  /**
   * 重新录音
   */
  reRecord() {
    this.showBtn(BTN.REC);
    this.isPause = false;
    this.tempFilePath = null;
    durationTimes = 0;
    clearInterval(this.recordingTimmer);
  },

  //播放声音
  playVoice() {
    if (!this.isPause) {
      audioConText.src = this.tempFilePath;
      audioConText.play();
    } else {
      audioConText.pause();
    }

  },
  /**
   * 从头播放
   */
  replayVoice() {
    audioConText.stop();
    audioConText.play();
  },

  /**
   * timeout 清除函数
   */
  clearTimmer() {
    clearTimeout(this.startTimer);
  },

  /**
   * 开始录音
   */
  startRecord() {
    recordMgr.start({
      duration: 10000,
      sampleRate: 44100,
      numberOfChannels: 1,
      encodeBitRate: 192000,
      format: 'aac',
      frameSize: 50
    });
  },

  pauseRecord() {
    recordMgr.pause();
  },

  stopRecord() {
    durationTimes = 0;
    clearInterval(this.recordingTimmer);
    recordMgr.stop();
  },

  onRecordStart() {
    this.showBtn(BTN.FINISH);
    durationTimes = 0;
    clearInterval(this.recordingTimmer);
    this.recordingTimmer = setInterval(() => {
      durationTimes += 1;
      this.setData({
        duration: durationTimes
      });
    }, TIME_DOWN_CYCLE);
  },

  onRecordPause() {
    console.log('暂停录音')
  },

  onPlay() {
    this.showBtn(BTN.PAUSE);
    this.isPause = true;
  },
  onPause() {
    this.isPause = false;
    this.showBtn(BTN.PLAY);
  },
  onEnded() {
    this.isPause = false;
    this.showBtn(BTN.PLAY);
  },
  /**
   * 停止录音事件
   */
  onRecordStop(resp) {
    const {
      tempFilePath
    } = resp;
    this.tempFilePath = tempFilePath;
    this.clearTimmer();
    wx.showToast({
      title: '录音结束',
      icon: 'success',
      duration: 1000,
      mask: true
    });
    this.showBtn(BTN.PLAY);
  },


  //上传录音
  upload() {
    wx.uploadFile({
      url: "http://10.10.11.58:8101/archermind-ai/audio-upload", //服务器地址
      filePath: this.tempFilePath,
      name: 'audioFile',
      header: {
        "Content-Type": "multipart/form-data"
      },
      formData: {
        userId: 'bing'//此处为登陆用户ID(userName)
      },
      success: function (res) {
        wx.showToast({
          title: '上传成功',
          icon: 'success',
          duration: 2000
        })
      },
      fail: function (res) {
      },
      complete: function (res) {

      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    clearInterval(timeDownTimer);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    durationTimes = 0;
    clearInterval(this.recordingTimmer);
    clearInterval(timeDownTimer);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})